package com.ease.database.initializer;

import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.ease.common.util.Detect;
import com.ease.common.util.FileUtil;
import com.ease.common.vo.MapParameter;
import com.ease.dao.JdbcTemplateDataAccessObject;
import com.obas.test.ApplicationContextUserContextTest;

/**
 * @author nathanleewei
 *
 */
public class DictionaryInitializer extends ApplicationContextUserContextTest {

	@Autowired
	JdbcTemplateDataAccessObject jdbcTemplateDataAccessObject;

	@Test
	public void test() {
		String string = FileUtil.readClassPathResourceToString(DictionaryInitializer.class, "dictionary.csv");

		String[] rows = StringUtils.delimitedListToStringArray(string, "\r\n");
		MapParameter parameter = null;
		if (null != rows) {
			for (String row : rows) {
				String[] values = StringUtils.commaDelimitedListToStringArray(row);
				if (null == values || values.length < 5) {
					continue;
				}
				String typename = Detect.trim(values[0]);
				String typecode = Detect.trim(values[1]);
				short value = Short.parseShort(Detect.trim(values[2]));
				String optionname = Detect.trim(values[3]);
				String optioncode = Detect.trim(values[4]).toUpperCase();

				//
				parameter = new MapParameter();
				parameter.put("code", typecode);

				List<Map<String, Object>> dictionaryTypes = jdbcTemplateDataAccessObject.find("SELECT * FROM MM_DICTIONARYTYPE T WHERE T.CODE=:code", parameter);
				if (!notEmpty(dictionaryTypes)) {
					parameter.put("name", typename);
					jdbcTemplateDataAccessObject.create("INSERT INTO MM_DICTIONARYTYPE(ID, CODE, NAME)VALUES(SEQ_MM_DICTIONARYTYPE.NEXTVAL, :code, :name)", parameter);
				}
				dictionaryTypes = jdbcTemplateDataAccessObject.find("SELECT * FROM MM_DICTIONARYTYPE T WHERE T.CODE=:code", parameter);
				Map<String, Object> dictionaryType = firstOne(dictionaryTypes);
				long dictionaryTypeId = Long.parseLong(String.valueOf(dictionaryType.get("ID")));
				//
				parameter = new MapParameter();
				parameter.put("name", optionname);
				parameter.put("code", optioncode);
				parameter.put("value", value);
				parameter.put("dictionaryTypeId", dictionaryTypeId);
				jdbcTemplateDataAccessObject.create(
						"INSERT INTO MM_DICTIONARYOPTION(ID, CODE, NAME,VALUE, DICTIONARYTYPE_ID)VALUES(SEQ_MM_DICTIONARYOPTION.NEXTVAL, :code, :name,:value, :dictionaryTypeId)", parameter);
			}
		}

	}

}
